﻿using Robot.DeviceTestTools.Entity.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Robot.DeviceTestTools
{
    public partial class FormMain : Form
    {
        #region 公共变量

        #endregion

        #region 构造函数

        public FormMain()
        {
            InitializeComponent();
        }

        #endregion

        #region 窗体事件

        /// <summary>
        /// 窗体初始化加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMain_Load(object sender, EventArgs e)
        {
            Initialization();
        }

        /// <summary>
        /// 主程序计时器事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerMain_Tick(object sender, EventArgs e)
        {
            if (checkBox_AutoRefresh.CheckState == CheckState.Checked)
            {
                button_Search.Enabled = false;
                UpdateNodeData();
            }
            else
            {
                button_Search.Enabled = true;
            }
        }

        /// <summary>
        /// 打开连接 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_OpenConnect_Click(object sender, EventArgs e)
        {
            try
            {
                (bool, string) result = Global.KepServer.ConnectServer(comboBox_Server.Text, textBox_IP.Text);
                if (result.Item1)
                {
                    UpdateControlStatus(true);

                    UpdateNodeData();

                    Log($"打开连接成功");
                    MessageBox.Show($"打开连接成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    Log($"打开连接失败");
                    MessageBox.Show($"打开连接失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Log($"发生异常，错误：{ex.Message}");
                MessageBox.Show($"发生异常\n\n错误：{ex.Message}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 关闭连接 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_CloseConnect_Click(object sender, EventArgs e)
        {
            try
            {
                Global.KepServer.DisconnectServer();

                UpdateControlStatus(false);

                Log($"关闭连接成功");
                MessageBox.Show($"关闭连接成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Log($"发生异常，错误：{ex.Message}");
                MessageBox.Show($"发生异常\n\n错误：{ex.Message}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 测试电化学测试仪器 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ShowElecMachines_Click(object sender, EventArgs e)
        {
            new FormElecMachines().Show();
        }

        /// <summary>
        /// 搜索点位 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Search_Click(object sender, EventArgs e)
        {
            UpdateNodeData();
        }

        /// <summary>
        /// 配置点位列表 单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_Node_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 点击标题栏不进行响应
            if (e.RowIndex == -1) { return; }

            // 当前选中的数据
            DataGridViewRow selectData = dataGridView_Node.Rows[e.RowIndex];

            switch (e.ColumnIndex)
            {
                case 1:
                    {
                        textBox_SetValue_NodeId.Text = selectData.Cells[1].Value.ToString();
                    }
                    break;
            }
        }

        /// <summary>
        /// 确认写入参数 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ConfirmSet_Click(object sender, EventArgs e)
        {
            try
            {
                Global.KepServer.Write(textBox_SetValue_NodeId.Text, textBox_SetValue_Value.Text);
                Log($"参数写入完成, 写入ID:【{textBox_SetValue_NodeId.Text}】, 写入值: {textBox_SetValue_Value.Text}");
            }
            catch (Exception ex)
            {
                Log($"发生异常，错误：{ex.Message}");
                MessageBox.Show($"发生异常\n\n错误：{ex.Message}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 自定义方法

        #region 页面功能初始化

        /// <summary>
        /// 页面功能初始化
        /// </summary>
        public void Initialization()
        {
            #region 初始化基础参数

            // 初始化 可用OPC服务器 下拉列表数据源
            List<string> OPCServerList = Global.KepServer.GetOPCServerList();
            if (OPCServerList.Count <= 0)
            {
                button_OpenConnect.Enabled = false;

                Log($"本机暂无可用OPC服务器, 无法进行测试");
                MessageBox.Show($"本机暂无可用OPC服务器, 无法进行测试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            OPCServerList.ForEach(item =>
            {
                comboBox_Server.Items.Add($"{item}");
            });
            comboBox_Server.SelectedIndex = 0;

            #endregion

            UpdateControlStatus(false);

            Log($"程序初始化完成");
        }

        #endregion

        #region 刷新可用点位列表

        /// <summary>
        /// 刷新可用点位列表
        /// </summary>
        public void UpdateNodeData()
        {
            Task.Run(() =>
            {
                Invoke(new EventHandler(delegate
                {
                    List<ValueModel> data = new List<ValueModel>();

                    if (!string.IsNullOrEmpty(textBox_Search_NodeId.Text))
                    {
                        data = Global.SaveNodeData.Where(w => w.Value.Tag.Contains(textBox_Search_NodeId.Text)).Select(s => s.Value).ToList();
                    }
                    else
                    {
                        data = Global.SaveNodeData.Select(s => s.Value).ToList();
                    }

                    dataGridView_Node.Rows.Clear();

                    int index;
                    foreach (var item in data)
                    {
                        index = dataGridView_Node.Rows.Add();
                        dataGridView_Node.Rows[index].Cells[0].Value = item.ClientHandle;
                        dataGridView_Node.Rows[index].Cells[1].Value = item.Tag;
                        dataGridView_Node.Rows[index].Cells[2].Value = item.Value;
                        dataGridView_Node.Rows[index].Cells[3].Value = item.Quanlity;
                        dataGridView_Node.Rows[index].Cells[4].Value = $"{item.Time:yyyy-MM-dd HH:mm:ss}";
                    }
                }));
            });
        }

        #endregion

        #region 更新页面控件状态

        /// <summary>
        /// 更新页面控件状态
        /// </summary>
        /// <param name="status">状态</param>
        public void UpdateControlStatus(bool status)
        {
            if (status)
            {
                button_OpenConnect.Enabled = false;
                button_CloseConnect.Enabled = true;
                textBox_Search_NodeId.Enabled = true;
                button_Search.Enabled = true;
                textBox_SetValue_NodeId.Enabled = true;
                textBox_SetValue_Value.Enabled = true;
                button_ConfirmSet.Enabled = true;
                checkBox_AutoRefresh.Enabled = true;
                timerMain.Enabled = true;
            }
            else
            {
                button_OpenConnect.Enabled = true;
                button_CloseConnect.Enabled = false;
                textBox_Search_NodeId.Enabled = false;
                button_Search.Enabled = false;
                textBox_SetValue_NodeId.Enabled = false;
                textBox_SetValue_Value.Enabled = false;
                button_ConfirmSet.Enabled = false;
                checkBox_AutoRefresh.Enabled = false;
                timerMain.Enabled = false;

                checkBox_AutoRefresh.CheckState = CheckState.Unchecked;
                dataGridView_Node.Rows.Clear();
            }
        }

        #endregion

        #region 更新Log日志控件内容

        /// <summary>
        /// 更新Log日志控件内容
        /// </summary>
        /// <param name="msg"></param>
        public void Log(string msg)
        {
            _ = Task.Run(() =>
            {
                Invoke(new MethodInvoker(() =>
                {
                    ListView_Log.Items.Insert(0, new ListViewItem() { Text = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {msg}", BackColor = Color.White });
                    ListView_Log.LabelWrap = true;
                    //ListView_Log.Focus();                                                                           // 聚焦光标
                    //ListView_Log.Items[ListView_Log.Items.Count - 1].Selected = true;      // 选中最后一行
                    //ListView_Log.Items[ListView_Log.Items.Count - 1].EnsureVisible();       // 显示内容自动滚动到最后一行
                }));
            });
        }

        #endregion

        #region 清空Log日志控件内容

        /// <summary>
        /// 清空Log日志控件内容
        /// </summary>
        public void ClearLog()
        {
            _ = Task.Run(() =>
            {
                Invoke(new MethodInvoker(() =>
                {
                    ListView_Log.Items.Clear();
                }));
            });
        }

        #endregion

        #endregion

    }
}
